package com.itheima.mm.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mm.common.QuestionConst;
import com.itheima.mm.context.BaseContext;
import com.itheima.mm.dto.QuestionDTO;
import com.itheima.mm.dto.QuestionGetByIdDTO;
import com.itheima.mm.entity.PageResult;
import com.itheima.mm.entity.QueryPageBean;
import com.itheima.mm.entity.QuestionPageQueryParams;
import com.itheima.mm.exception.BaseException;
import com.itheima.mm.mapper.*;
import com.itheima.mm.pojo.*;
import com.itheima.mm.service.QuestionService;
import com.itheima.mm.utils.DateUtils;
import com.itheima.mm.vo.QuestionMMVO;
import com.itheima.mm.vo.QuestionVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


//@Description QuestionServiceImpl
 //@Author xiao
 //@Date 2024-06-25


@Service
public class QuestionServiceImpl implements QuestionService {

    //添加或者更新试题依赖
    @Autowired
    private QuestionMapper questionMapper;

    //添加或者更新题选项
    @Autowired
    private QuestionItemMapper questionItemMapper;

    //添加或者更新题标签
    @Autowired
    private QuestionTagMapper questionTagMapper;


    //公司，行业的依赖
    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private CompanyIndustryMapper companyIndustryMapper;
    //引入题状态类，用与删除
    @Autowired
    private QuestionReviewLogMapper questionReviewLogMapper;




    //试题预览：

    @Resource
    private CatalogMapper catalogMapper;

    @Resource
    private IndustryMapper industryMapper;

    @Resource
    private TagMapper tagMapper;


    /**
     * 根据id和是否精选查询题目数据
     *
     * @param questionGetByIdDTO
     * @return
     */
    @Override
    public QuestionVO getById(QuestionGetByIdDTO questionGetByIdDTO) {
        QuestionVO questionVO = questionMapper.getById(questionGetByIdDTO);
        Integer catalogId = questionVO.getCatalogId();
        Catalog catalog = catalogMapper.getById(catalogId);
        questionVO.setCatalog(catalog);
        Company company = companyMapper.getById(questionVO.getCompanyId());
        List<Industry> industryList = industryMapper.selectIndustryListByCompany(company.getId());
        List<String> industryNameList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(industryList)){
            industryNameList = industryList.stream().map(Industry::getName).collect(Collectors.toList());
        }
        company.setIndustryList(industryList);
        company.setIndustryNameList(industryNameList);
        questionVO.setCompany(company);
        List<QuestionItem> questionItemList = questionItemMapper.getListByQuestionId(questionVO.getId());
        questionVO.setQuestionItemList(questionItemList);
        List<Tag> tagList = tagMapper.findListByQuestionId(questionVO.getId());
        List<String> tagNameList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(tagList)){
            tagNameList = tagList.stream().map(Tag::getName).collect(Collectors.toList());
        }
        questionVO.setTagList(tagList);
        questionVO.setTagNameList(tagNameList);

        return questionVO;
    }



    //删除试题
    @Override
    public void deleteById(Integer questionId) {

        questionItemMapper.deleteById(questionId);
        questionTagMapper.deleteByQuestionId(questionId);
        questionReviewLogMapper.deleteById(questionId);
        questionMapper.deleteById(questionId);

    }






    /**分页查询精选题列表数*/

    @Resource
    private ReviewLogMapper reviewLogMapper;

    @Override
    public PageResult findClassicListByPage(QueryPageBean<QuestionPageQueryParams> queryPageBean) {

        QuestionPageQueryParams queryParams = queryPageBean.getQueryParams();
        if(queryParams==null){
            queryParams = new QuestionPageQueryParams();
        }
        queryParams.setIsClassic(1);
        //设置分页查询参数
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());

        //执行查询数据

        List<QuestionMMVO> questionMMVOList =  questionMapper.findByCondition2(queryParams);
        Page<QuestionMMVO> page = (Page<QuestionMMVO>) questionMMVOList;

        for (QuestionMMVO questionMMVO : questionMMVOList) {
            ReviewLog reviewLog = reviewLogMapper.getByQuestionId(questionMMVO.getId());
            if(reviewLog==null){
                reviewLog = new ReviewLog();
            }
            questionMMVO.setReviewLog(reviewLog);
        }

        //返回数据封装
        return new PageResult(page.getTotal(),page.getResult());
    }

    //加入精选试题
    @Override
    public void updateClassic(Integer questionId) {
        Question question = new Question();
        question.setIsClassic(1);
        question.setId(questionId);
        questionMapper.update(question);
    }











    //根据条件查询试题
    @Override
    public PageResult<QuestionMMVO> findListByPage(QueryPageBean<QuestionPageQueryParams> queryPageBean) {

        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());


        Page<QuestionMMVO> page = questionMapper.findByCondition(queryPageBean.getQueryParams());

        PageResult<QuestionMMVO> pageResult = new PageResult<>(page.getTotal(),page.getResult());

        return pageResult;
    }


    // //添加或者更新试题
    //引用内存数据
    @Transactional
    @Override
    public void addOrUpdate(QuestionDTO questionDTO) {
        Question question = new Question();
        //利用工具类是其前端传来的数据对象QuestionDTO属性赋值到question对象中
        BeanUtils.copyProperties(questionDTO,question);
       //1.添加或更新学科，在以下定义方法；
       addOrUpdateQuestion(question);

       //2.添加或更新题选项
        //将question对象的ID从新赋值回给questionDTO对象属性
        questionDTO.setId(question.getId());
        //调用更新选项方法
        addOrUpdateQuestionItem(questionDTO);


        //3.更新标签信息
        //传入question ID ，与对应的标签列表数据
        addOrUpdateQuestionTag(question.getId(),questionDTO.getTagList());

        //4.更新企业和行业信息
        //获取前端传来的企业消息列表
        addOrUpdateCompanyAndIndustry(questionDTO.getCompany());


    }

    //添加或新增试题方法
    public void addOrUpdateQuestion(Question question) {
        //新增添加试题
        if (question.getId() == null || question.getId() == 0) {
            //通过工具类获取ww-ww-ww格式的当前时间，并封装到question对象中，存入数据库
            question.setCreateDate(DateUtils.parseDate2String(new Date()));

            //从内存中获取当前用户Id，并封装到question对象中，存入数据库
            question.setUserId(BaseContext.getCurrentId());

            //获取枚举常量的序号，获取当前题目状态，并封装到question对象的status属性中，存入数据
            question.setStatus(QuestionConst.Status.PRE_PUBLISH.ordinal());


            //从枚举获取当前审核状态，并封装到question对象中，存入数据库
            question.setReviewStatus(QuestionConst.ReviewStatus.PRE_REVIEW.ordinal());

            //封装好进行添加
            questionMapper.add(question);
        } else {
            //更新试题数据
            questionMapper.update(question);
        }


    }


    //新增或更新题选项
    public void addOrUpdateQuestionItem(QuestionDTO questionDTO){
        //获取题目选项列表
        List<QuestionItem> questionItemList = questionDTO.getQuestionItemList();
        //判断题目选项列表是否为空，为空表示没有题目选项，添加或者更新失败
        if(CollectionUtils.isEmpty(questionItemList)){
            throw new BaseException("新增或更新题失败，题的选项不能为空");
        }
        questionItemList.forEach(questionItem -> {
            //为每一个题选项添加 题id
            questionItem.setQuestionId(questionDTO.getId());
            //判断选项列表里的单个选项是否有内容，
            if(!ObjectUtils.isEmpty(questionItem.getContent())){
                //判断选项的id是否为空，为空为新增，不为空则为更新
                if(questionItem.getId()==null || questionItem.getId()==0){
                    //选项新增
                    questionItemMapper.add(questionItem);
                }else{
                    //选项更新
                    questionItemMapper.update(questionItem);
                }
            }
        });
    }



    //添加题目与标签的关系数据
    public void addOrUpdateQuestionTag(Integer questionId,List<Tag> tagList){

        //如果对应问题的标签列表数据不为空时，将删除标签数据
        if(!CollectionUtils.isEmpty(tagList)){
            questionTagMapper.deleteByQuestionId(questionId);
        }
            //遍历标签列表里的每一个标签
        tagList.forEach(tag -> {
            //创建一个问题id，标签id对象，
            QuestionTag questionTag = new QuestionTag();
            //赋值问题id
            questionTag.setQuestionId(questionId);
            //赋值标签id
            questionTag.setTagId(tag.getId());
            //添加数据至数据库
            questionTagMapper.add(questionTag);
        });
    };



    /**
     * 更新企业和行业信息
     * @param company
     */
    private void addOrUpdateCompanyAndIndustry(Company company) {
        //判断前端传入的企业数据是否为空
        if(!ObjectUtils.isEmpty(company)){
            //企业数据不为空，判断是否有企业id
            if(company.getId()!=null && company.getId()>0){
                //赋值，添加用户的id
                company.setUserId(BaseContext.getCurrentId());
                //更新企业的信息，传入更改的信息
                companyMapper.update(company);
                //获取该企业的 行业列表数据
                List<Industry> industryList = company.getIndustryList();
                //行业列表数据不为空
                if(!CollectionUtils.isEmpty(industryList)) {

                    //利用企业id，删除企业与行业方向多对多的数据
                    companyIndustryMapper.deleteByCompanyId(company.getId());

                    //重新插入企业与行业方向多对多的数据
                    //遍历该企业的每一个行业id
                    industryList.forEach(industry -> {
                        //创建一个企业id与行业id关系的对象；
                        CompanyIndustry companyIndustry = new CompanyIndustry();
                        //为该对象赋值，添加企业id
                        companyIndustry.setCompanyId(company.getId());
                        //为该对象添加当次循环的行业id
                        companyIndustry.setIndustryId(industry.getId());
                        //添加关系数据
                        companyIndustryMapper.add(companyIndustry);
                    });
                }
            }
        }
    }




}
